package com.zyr.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zyr.filter.TokenTranslationFilter;
import com.zyr.handler.CustomerAccessDeineHandler;
import com.zyr.handler.LoginFailureHandler;
import com.zyr.constraint.AuthConstants;
import com.zyr.constraint.HttpConstants;

import com.zyr.model.Result;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;

import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;


import java.io.PrintWriter;


/**
 * @author 张雨润
 * @date 2024/7/25 下午8:21
 * @Description Security配置类
 */
@Slf4j
@Configuration
@EnableMethodSecurity
public class WebSecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // 由于使用token认证，关闭一跨域请求伪造，csrf防御，session管理
        http.csrf(AbstractHttpConfigurer::disable)
                .cors(AbstractHttpConfigurer::disable)
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
        //
        http
                .exceptionHandling(e->{
                    //未认证返回登录页处理
                    e.authenticationEntryPoint(new LoginFailureHandler());
                    //无权限访问处理
                    e.accessDeniedHandler(new CustomerAccessDeineHandler());
                });
        // 对所有请求身份验证
        http.authorizeHttpRequests(auth -> auth
                .requestMatchers(AuthConstants.LOGIN_URL).permitAll()
                .anyRequest().authenticated());
        return http.build();
    }


    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 认证器
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    // 登出成功
    @Bean
    public LogoutSuccessHandler logoutSuccessHandler(StringRedisTemplate stringRedisTemplate) {
        return ((request, response, authentication) -> {
            response.setContentType(HttpConstants.application_json);
            response.setCharacterEncoding(HttpConstants.UTF_8);
            // 删除redis中的token
            String authorization = request.getHeader(AuthConstants.AUTHORIZATION);
            String token = authorization.replaceFirst(AuthConstants.BEARER, "");
            stringRedisTemplate.delete(AuthConstants.LOGIN_TOKEN_PREFIX + token);
            Result<Object> result = Result.success();
            ObjectMapper objectMapper = new ObjectMapper();
            PrintWriter out = response.getWriter();
            out.write(objectMapper.writeValueAsString(result));
        });
    }
}
